<script setup lang="ts" name="InfraCronJobLog">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { formatDate } from '@/utils/dateUtil'
import { CronJobApi, CronJobLogType } from '@/api/infra/cronJob'
import { dataToFile } from '@/components/Excel/src/helper'
import CronJobLogDetail from './CronJobLogDetail.vue'
import { checkPermit } from '@/utils/permit'
import { DICT_TYPE } from '@/enums/dictEnums'
import { getIntDictOptions } from '@/utils/dict'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const { query } = useRoute() // 查询参数
const total = ref<number>(0) // 列表的总页数
const list = ref<CronJobLogType[]>([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  jobId: query.id as number | null,
  handlerName: undefined,
  beginTime: [],
  status: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await CronJobApi.Log.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageIndex: 1,
    pageSize: 20,
    jobId: query.id as number | null,
    handlerName: undefined,
    beginTime: [],
    status: undefined
  }
  handleQuery()
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: t('common', 'id') },
  { key: 'jobId', value: t('infra.cronJob.log', 'jobId') },
  { key: 'status', value: t('infra.cronJob', 'status') },
  { key: 'handlerName', value: t('infra.cronJob', 'handlerName') },
  { key: 'handlerParam', value: t('infra.cronJob', 'handlerParam') },
  { key: 'executeIndex', value: t('infra.cronJob.log', 'executeIndex') },
  { key: 'beginTime', value: t('infra.cronJob.log', 'beginTime') },
  { key: 'endTime', value: t('infra.cronJob.log', 'endTime') },
  { key: 'duration', value: t('infra.cronJob.log', 'duration') },
  { key: 'result', value: t('infra.cronJob.log', 'result') },
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await CronJobApi.Log.export(queryParams.value)
    dataToFile(allList, res)
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('infra.cronJob', 'handlerName')" prop="handlerName" class="!w-250px">
            <el-input v-model="queryParams.handlerName" :placeholder="t('infra.cronJob.rules', 'handlerName')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('infra.cronJob', 'status')" prop="status">
            <el-select v-model="queryParams.status" class="!w-160px" clearable :placeholder="t('infra.cronJob.rules', 'status')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.INFRA_CRON_JOB_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem :label="t('infra.cronJob.log', 'beginTime')" prop="beginTime">
            <el-date-picker
              v-model="queryParams.beginTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action',
              'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset')
            }}</el-button>
            <CButton v-if="checkPermit(['infra:cron-job-log:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column prop="id" :label="t('common', 'id')" width="120" align="center" />
          <el-table-column prop="jobId" :label="t('infra.cronJob.log', 'jobId')" align="center" />
          <el-table-column prop="handlerName" :label="t('infra.cronJob', 'handlerName')" align="center" />
          <el-table-column prop="handlerParam" :label="t('infra.cronJob', 'handlerParam')" align="center" />
          <el-table-column prop="executeIndex" :label="t('infra.cronJob.log', 'executeIndex')" align="center" />
          <el-table-column :label="t('infra.cronJob.log', 'dateTime')" align="center" width="330">
            <template #default="scope">
              <span>{{ formatDate(scope.row.beginTime) + ' ~ ' + formatDate(scope.row.endTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('infra.cronJob.log', 'duration')" align="center" prop="duration">
            <template #default="scope">
              <span>{{ t('infra.cronJob', 'ms', [scope.row.duration]) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('infra.cronJob', 'status')" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_CRON_JOB_LOG_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column prop="operate" :label="t('common', 'operate')" width="90" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" @click="openDetail(scope.row.id)">{{ t('action', 'detail') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <CronJobLogDetail ref="detailRef" />
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('infra.cronJob.log', 'title')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
